package tetris.game;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

public class GamePanel extends JPanel implements Runnable, KeyListener {
	private static final long serialVersionUID = 1L;
	private Game game = new Game();
	private long m_Now = 0;
	private long m_Soon = 0;
	
	public GamePanel(){
		Thread t = new Thread(this);
		addKeyListener(this);
		t.start();
		}
	
	Font gameFont = new Font("Impact", Font.PLAIN, 15);
	
	public void paintComponent(Graphics g)
	{
		g.setColor(Color.white);
		g.fillRect(0, 0, getWidth(), getHeight());
		game.DrawWellComplete(g);
		game.m_Piece.Draw(g);
		game.m_NextPiece.Draw(g);
	}
	
		public void run()
		{
			System.currentTimeMillis();
			while(game.isRunning())
			{
				//The current time (m_Now) is set every loop
				m_Now = System.currentTimeMillis();
				m_Soon = m_Now + 1000;
				
				while(game.m_input == false && System.currentTimeMillis() < m_Soon)
				{
					try{	Thread.sleep(1);	}catch(Exception e){}
				}
				
				//Check for Input... sort of...
				if (game.m_input == true)
				{
					game.m_input = false;
					//If the player pressed a button, we need to reset the gravity timer
					m_Soon = m_Now + 1000;
				}
				else
				{
					//*The bug Robert referred to in class is fixed by putting the solidify check first
					if(game.CheckSolidify())
					{
						//If there was a piece / piece is at the bottom then we stamp to the well
						game.Solidify();
						//Check if any rows are filled
						game.CheckRows();
						//Put up a new piece
						game.SwapPieces();
					}
					else
					{
						//*And then the movement 
						//Push the piece down (gravity)
						game.Input('s');
					}
				}
				
				repaint();
			}
		}
		
		public void keyPressed(KeyEvent ke) 
		{
			game.m_input = true;
			int inputBuffer = ke.getKeyChar();
			switch(ke.getKeyCode())
			{
			case KeyEvent.VK_LEFT:	inputBuffer = 'a';	break;
			case KeyEvent.VK_DOWN:	inputBuffer = 's';	break;
			case KeyEvent.VK_RIGHT:	inputBuffer = 'd';	break;
			case KeyEvent.VK_Q:		inputBuffer = 'q';	break;
			case KeyEvent.VK_E:		inputBuffer = 'e';	break;
			case KeyEvent.VK_ESCAPE:inputBuffer = 27;	break;
			case KeyEvent.VK_SPACE: inputBuffer = 32;	break;
			case KeyEvent.VK_W:		break;
			case KeyEvent.VK_A:		break;
			case KeyEvent.VK_S:		break;
			case KeyEvent.VK_D:		break;
			default:
				game.m_input = false;
			}
			game.Input(inputBuffer);
		}


		public void keyReleased(KeyEvent e) {

			
		}

		public void keyTyped(KeyEvent e) {
			
		}

}
